package com.newtouch.xcd.pms.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.newtouch.xcd.common.constants.ResponseCode;
import com.newtouch.xcd.common.to.CommonResult;
import com.newtouch.xcd.pms.service.SmsService;
import com.newtouch.xcd.pms.to.AlibabaSmsClientResult;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 短信微服务 实现
 */
@Component
@Service
public class SmsServiceImpl implements SmsService {

    /**
     * 发送新财道系统短信验证码
     * @param phone 手机号
     * @param smsCode   验证码
     * @return
     */
    @Override
    public CommonResult sentXcdLoginSmsCode(String phone, String smsCode) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4G5D3pSKaHYk15LZFfXw", "DYbSyqFiDfdCwVXiu2g8aMTE9yLyuh");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("TemplateCode", "SMS_195585397");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "新财道");

        Map map = new HashMap();
        map.put("code", smsCode);

        request.putQueryParameter("TemplateParam", JSONUtil.toJsonStr(map));
        CommonResponse response;
        try {
            response = client.getCommonResponse(request);
            String data = response.getData();
            AlibabaSmsClientResult alibabaSmsClientResult = JSONUtil.toBean(JSONUtil.parseObj(data), AlibabaSmsClientResult.class);
            String code =alibabaSmsClientResult.getCode();
            String message = alibabaSmsClientResult.getMessage();
            if(!"OK".equals(code)){
                return CommonResult.error(ResponseCode.R500.getCode(),"短信平台错误码："+code+"，错误信息："+message);
            }
            System.out.println(response.getData());
            return CommonResult.success(alibabaSmsClientResult);
        } catch (Exception e) {
            return CommonResult.error(ResponseCode.R500.getCode(),"短信服务器连接异常。");
        }
    }
}
